import { WebSocketServer, WebSocket } from 'ws';
import { parse as parseUrl } from 'url';
import http from 'http';

// 创建HTTP服务器
const server = http.createServer((req, res) => {
  // 设置CORS头
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  
  // 处理预检请求
  if (req.method === 'OPTIONS') {
    res.writeHead(204);
    res.end();
    return;
  }
  
  res.writeHead(404);
  res.end();
});

// 创建WebSocket服务器，使用HTTP服务器
const wss = new WebSocketServer({ server });

// 存储房间和连接
const rooms = new Map();
const chatUsers = new Map(); // 存储聊天用户 {roomId: Set<clientId>}

console.log('WebRTC信令服务器运行在端口 9001');

wss.on('connection', (ws, req) => {
  console.log('新的WebSocket连接');
  
  // 从URL中提取房间ID
  const pathname = parseUrl(req.url).pathname;
  const roomMatch = pathname.match(/\/room\/(.+)/);
  const roomId = roomMatch ? roomMatch[1] : null;
  
  let clientId = generateClientId();
  
  if (!roomId) {
    ws.close(1008, '无效的房间ID');
    return;
  }
  
  console.log(`客户端 ${clientId} 尝试连接房间 ${roomId}`);
  
  ws.on('message', (message) => {
    try {
      const data = JSON.parse(message);
      console.log('收到消息:', data.type, '来自:', clientId);
      
      switch (data.type) {
        case 'chat-message':
          handleChatMessage(data, roomId, clientId);
          break;
        case 'user-join':
          handleUserJoin(ws, roomId, clientId);
          break;
        case 'offer':
          handleWebRTCSignaling(data, roomId, clientId);
          break;
        case 'answer':
          handleWebRTCSignaling(data, roomId, clientId);
          break;
        case 'ice-candidate':
          handleWebRTCSignaling(data, roomId, clientId);
          break;
        default:
          console.log('未知消息类型:', data.type);
      }
    } catch (error) {
      console.error('解析消息失败:', error);
    }
  });
  
  ws.on('close', () => {
    console.log(`WebSocket连接关闭: ${clientId}`);
    handleDisconnection(roomId, clientId);
  });
  
  ws.on('error', (error) => {
    console.error('WebSocket错误:', error);
  });
  
  // 用户加入聊天室
  function handleUserJoin(ws, roomId, clientId) {
    if (!rooms.has(roomId)) {
      rooms.set(roomId, new Map());
    }
    
    if (!chatUsers.has(roomId)) {
      chatUsers.set(roomId, new Set());
    }
    
    const room = rooms.get(roomId);
    const users = chatUsers.get(roomId);
    
    room.set(clientId, { ws, type: 'user' });
    users.add(clientId);
    
    console.log(`用户加入: 房间 ${roomId}, 用户 ${clientId}`);
    
    // 发送欢迎消息
    ws.send(JSON.stringify({
      type: 'system-message',
      data: {
        message: `欢迎来到聊天室！当前在线用户: ${users.size} 人`
      }
    }));
    
    // 广播用户加入消息给其他用户
    broadcastToRoom(roomId, {
      type: 'system-message',
      data: {
        message: `用户 ${clientId} 加入了聊天室`
      }
    }, clientId);
  }
  
  // 处理聊天消息
  function handleChatMessage(data, roomId, clientId) {
    if (rooms.has(roomId)) {
      broadcastToRoom(roomId, {
        type: 'chat-message',
        data: {
          userId: clientId,
          message: data.data.message,
          timestamp: data.data.timestamp
        }
      }, clientId);
    }
  }
  
  // 处理WebRTC信令消息
  function handleWebRTCSignaling(data, roomId, clientId) {
    console.log(`处理WebRTC信令: ${data.type} 来自房间 ${roomId} 客户端 ${clientId}`);
    
    if (rooms.has(roomId)) {
      const room = rooms.get(roomId);
      console.log(`房间 ${roomId} 中的用户数量: ${room.size}`);
      console.log(`房间中的用户:`, Array.from(room.keys()));
      
      // 将信令消息转发给房间内的其他客户端
      const messageToSend = {
        type: data.type,
        data: {
          offer: data.offer,
          answer: data.answer,
          candidate: data.candidate
        },
        fromClientId: clientId
      };
      
      console.log(`准备转发消息:`, messageToSend.type);
      broadcastToRoom(roomId, messageToSend, clientId);
    } else {
      console.log(`房间 ${roomId} 不存在`);
    }
  }
  
  // 处理断开连接
  function handleDisconnection(roomId, clientId) {
    if (rooms.has(roomId)) {
      const room = rooms.get(roomId);
      room.delete(clientId);
      
      if (chatUsers.has(roomId)) {
        const users = chatUsers.get(roomId);
        users.delete(clientId);
        
        // 广播用户离开消息
        broadcastToRoom(roomId, {
          type: 'system-message',
          data: {
            message: `用户 ${clientId} 离开了聊天室`
          }
        });
      }
      
      // 如果房间空了，删除房间
      if (room.size === 0) {
        rooms.delete(roomId);
        chatUsers.delete(roomId);
        console.log(`房间 ${roomId} 已清空`);
      }
    }
  }
});

// 向房间广播消息
function broadcastToRoom(roomId, message, excludeClientId = null) {
  if (rooms.has(roomId)) {
    const room = rooms.get(roomId);
    console.log(`广播消息到房间 ${roomId}, 排除客户端: ${excludeClientId}`);
    console.log(`房间中的客户端数量: ${room.size}`);
    
    let sentCount = 0;
    room.forEach((client, clientId) => {
      if (clientId !== excludeClientId && client.ws.readyState === WebSocket.OPEN) {
        console.log(`发送消息给客户端: ${clientId}`);
        client.ws.send(JSON.stringify(message));
        sentCount++;
      } else {
        console.log(`跳过客户端 ${clientId}: 状态=${client.ws.readyState}, 排除=${clientId === excludeClientId}`);
      }
    });
    
    console.log(`成功发送消息给 ${sentCount} 个客户端`);
  } else {
    console.log(`房间 ${roomId} 不存在，无法广播消息`);
  }
}

// 生成客户端ID
function generateClientId() {
  return 'client_' + Math.random().toString(36).substr(2, 9);
}

// 监听端口
server.listen(9001, '0.0.0.0', () => {
  console.log('聊天服务器运行在端口 9001');
  console.log('服务器地址: 0.0.0.0:9001');
  console.log('外部访问地址: http://192.168.8.41:9001');
});